package com.hs.test_push2_server.utils;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

import java.io.*;
import java.net.MalformedURLException;

public class TestM {

    public static void main(String[] args) {
        SmbFile[] sharedFileList = getSharedFileList("smb://10.120.201.10/testre/");
        for (SmbFile smbFile : sharedFileList) {
            System.out.println(smbFile.getName());

            downloadFileToFolder("smb://10.120.201.10/testre/",
                    smbFile.getName(),"D://as/",smbFile.getName());
        }


    }

    /**
     * 读取共享文件夹下的所有文件(文件夹)的名称
     *
     * @param "smb://192.168.1.215/ecg/2022-09-29/
     */
    public static SmbFile[] getSharedFileList(String smbFileUrl) {
        SmbFile smbFile;
        try {
            smbFile = new SmbFile(smbFileUrl);
            if (!smbFile.exists()) {
                System.out.println("文件夹不存在");
            } else {
                SmbFile[] files = smbFile.listFiles();
                return files;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SmbException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 下载文件到指定文件夹
     * @param remoteUrl 远程文件夹路径
     * @param fileName 文件名称
     * @param localDir 要下载到本地的路径
     * @param localFileName 下载到本地的文件重命名名称
     */
    public static void downloadFileToFolder(String remoteUrl, String fileName, String localDir, String localFileName) {
        InputStream in = null;
        OutputStream out = null;
        try {
            File dir = new File(localDir);
            if(!dir.exists()){
                dir.mkdir();
            }
            SmbFile remoteFile = new SmbFile(remoteUrl  + "/" + fileName);
            File localFile = new File(localDir + "/" + localFileName);
            in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
